<?php

namespace app\api\model;

use app\common\library\wechat\WxUser;
use \app\api\model\Wxapp;
use \app\api\model\Setting as SettingModel;

class Message extends WxUser
{
    /**
     * 获取微信请求接口token
     * @return mixed
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
   public function getToken()
    {
        $accessToken = $this->getAccessToken();
        return $accessToken;
    }

    /**
     * 微信支付成功接口通知
     * @param $data
     * @return false|void
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function sendMessage($data){
        $detail = SettingModel::get(['key'=>'openId']);
        $token = $this->getToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $token;
        if(empty($detail)){
            return false;
        }
        $wxInfo = $detail['values'];
        $openids = explode(',',$wxInfo['openid']);
        $param = [
            //'touser' => $wxInfo['openid'],
            'template_id' => $wxInfo['template_id'],
            'data' => [
                'first' => [
                    'value' => $data['first'],
                    'color' => '#575757',
                ],
                'keyword1' => [
                    'value' => $data['keyword1'],
                    'color' => '#575757',
                ],
                'keyword2' => [
                    'value' => $data['keyword2'],
                    'color' => '#FF0000',
                ],
                'keyword3' => [
                    'value' => $data['keyword3'],
                    'color' => '#FF0000',
                ],
                'keyword4' => [
                    'value' => $data['keyword4'],
                    'color' => '#FF0000',
                ],
                'remark' => [
                    'value' => $data['remark'],
                    'color' => '#575757',
                ],
            ],
        ];
        $result = false;
        if(!empty($openids) && is_array($openids)){
            foreach ($openids as $key=>$val){
                $param['touser'] = $val;
                $result = $this->post($url, json_encode($param));
            }
        }

        //$result = $this->post($url, json_encode($param));
        return $result;
    }

}